import { AnyAction, Reducer } from 'redux';
import { message } from 'antd';
import { EffectsCommandMap } from 'dva';
import { fetchValidation } from '@/utils';
import {
  queryBoxManagementList,
  downloadFile,
  queryGardenList,
  operChangeStatus,
  queryBluetooth,
  queryFirmware,
} from './service';

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: {}) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: {};
  effects: {
    fetch: Effect;
    fetchEdition: Effect;
    downFile: Effect;
    fetchGarden: Effect;
    changeStatus: Effect;
  };
  reducers: {
    save: Reducer;
    saveGarden: Reducer;
    saveEdition: Reducer;
    clearGarden: Reducer;
  };
}

const stateInfo = {
  dataInfo: {
    list: [],
    count: 0,
  },
  gardenList: [],
  bluetooth: [],
  firmware: [],
};

const Model: ModelType = {
  namespace: 'boxManagementList',

  state: stateInfo,

  effects: {
    * fetch({ payload }, { call, put }) {
      const response = yield call(queryBoxManagementList, payload);
      const data = fetchValidation(response);
      yield data && put({
        type: 'save',
        payload: response.body,
      });
    },

    * fetchEdition({ payload }, { call, put }) {
      const bluetooth = yield call(queryBluetooth, payload);
      const firmware = yield call(queryFirmware, payload);
      yield put({
        type: 'saveEdition',
        payload: { bluetooth: Object.values(bluetooth.body) },
      });
      yield put({
        type: 'saveEdition',
        payload: { firmware: Object.values(firmware.body) },
      });
    },

    * downFile({ payload }, { call }) {
      yield call(downloadFile, payload);
    },

    * fetchGarden({ payload }, { call, put }) {
      const response = yield call(queryGardenList, payload);
      const data = fetchValidation(response);
      yield data && put({
        type: 'saveGarden',
        payload: data.body && data.body.list ? data.body.list : [],
      });
    },

    * changeStatus({ payload: { search, ...query } }, { call, put }) {
      const response = yield call(operChangeStatus, query);
      const data = fetchValidation(response);
      if (data) {
        message.success('设置成功');
        yield put({
          type: 'fetch',
          payload: search,
        });
      }
    },
  },

  reducers: {
    save(state, { payload }) {
      return {
        ...state,
        dataInfo: payload,
      };
    },

    saveGarden(state, { payload }) {
      return {
        ...state,
        gardenList: payload,
      };
    },

    saveEdition(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },

    clearGarden(state) {
      return ({
        ...state,
        gardenList: [],
      });
    },
  },
};

export default Model;
